<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/02/28
 */
namespace common\logic;

use common\logic\Cabin;
use common\logic\Occupancy;
use common\models\Booker;
use common\tool\Currency;
use yii;
use common\models\Trip as TripModel;
use common\models\User;

class Trip {

    public static function getBoatId($tripId) {
        return TripModel::getScalar("id=$tripId", 'boat_id');
    }

    public static function getCabinsByTripId($tripId) {
        $boatInfo = TripModel::getOne("id=$tripId", 'boat_id,free_spaces');
        $r = Cabin::getCabins($boatInfo['boat_id']);
        $cabins = [];
        foreach ($r as $k => $v) {
            $cabinPriceNum=self::cabinPriceNum($tripId, $v['id']);
            if($cabinPriceNum){//存在Occupancy没更新过来的情况(原因是可能没空床位了)
                $cabins[] = [
                        "cabinId" => $v['id'],
                        //'type' => $v['name_en'],
                        "roomName" => $v['name_cn'],
                        "size" => 0,
                        //$v['size'],//TODO
                        "bedding" => $v['bedding_cn'],
                        "bathRoom" => (bool)$v['bathroom'],
                        "maxCount" => $v['occupancy'],
                        "avaliableCount" => 1,
                        "cabinCount" => (int)$v['cabin_number'],
                        "deck" => $v['deck_cn'],
                        "aircon" => (bool)$v['aircon'],
                        'imageUrl' => $v['img'],
                    ] + $cabinPriceNum;
            }
        }
        return $cabins;
    }

    public static function cabinPriceNum($tripId, $cabinId) {
        $res = [];
        //$trip = TripModel::getOne("id=$tripId");
        //$cabin = Cabin::getOneCabin($cabinId);
        $occupancies = Occupancy::getOccupanciesByTripCabin($tripId, $cabinId);
        foreach ($occupancies as $occupancy) {
            $origPrice = [
                'value' => (int)$occupancy['price'],
                'unit' => '€',
            ];
            $price = [
                'value' => ceil(Currency::eur2cnyYuan($occupancy['price'])),
                'unit' => '￥',
            ];
            switch ($occupancy['name_en']) {
                case 'Single Occupancy':
                    $res['oneself'] = [
                        'step' => 1,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
                case 'Double Occupancy':
                    if (empty($res['share'])) {
                        $res['share'] = [
                            'step' => 2,
                            'max' => (int)$occupancy['free_spaces'],
                            'price' => $price,
                            'origPrice' => $origPrice,
                        ];
                    }
                    break;
                case 'Twin Share':
                    $res['share'] = [
                        'step' => 1,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
                case 'Triple Occupancy':
                    $res['share'] = [
                        'step' => 3,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
                case 'Triple Share':
                    $res['share'] = [
                        'step' => 1,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
                case 'Quad Occupancy':
                    $res['share'] = [
                        'step' => 4,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
                case 'Quad Share':
                    $res['share'] = [
                        'step' => 1,
                        'max' => (int)$occupancy['free_spaces'],
                        'price' => $price,
                        'origPrice' => $origPrice,
                    ];
                    break;
            }
        }
        return $res;
    }

    public static function getTrips($boatId, $startDate, $endDate, $o = 0, $l = 10) {
        $today = date('Y-m-d');
        if (!$startDate || $startDate < $today) $startDate = $today;
        $where = "boat_id=$boatId AND start_time>='$startDate 00:00:00' AND tour_id<>0";//抓取过程中 tour_id还没更新的 先不展示
        if ($endDate) $where .= " AND end_time<='$endDate 00:00:00'";
        $where .= ' AND booker_sync<>\'' . Booker::SYNC_DELETED . '\'';
        $tripData = TripModel::getList($where, '*', 'start_time', $o, $l + 1);
        $more = !empty($tripData[$l]);
        unset($tripData[$l]);
        $trips = self::format($tripData);
        return [
            'list' => $trips,
            'more' => $more,
            'features' => [],
            'boatName' => '',
            'boatImage' => '',
        ];
    }

    public static function getTripsForSearch($boatIds = [], $startDate, $endDate) {
        $tripsMap = [];
        $tripIds = [];
        $today = date('Y-m-d');
        if (!$startDate || $startDate < $today) $startDate = $today;
        //$where = "start_time>='$startDate 00:00:00' AND tour_id<>0";//正常
        $where = "end_time>='$startDate 00:00:00' AND tour_id<>0";//宽松条件
        //if ($endDate) $where .= " AND end_time<='$endDate 00:00:00'";
        if ($endDate) $where .= " AND start_time<='$endDate 00:00:00'";
        foreach ($boatIds as $boatId) {
            $r = TripModel::getDb()->createCommand("SELECT a.id,a.boat_id,a.tour_id,a.name_cn,a.name_en,a.start_time,a.end_time,a.free_spaces,
b.duration,b.nights,b.dives,b.arrival_cn,b.departure_cn,b.desc_cn
FROM `dive_trip` AS a JOIN `dive_tour` AS b ON a.tour_id=b.id WHERE a.boat_id=$boatId AND $where ORDER BY a.start_time LIMIT 3")->queryAll();
            foreach ($r as $k => $v) {
                $r[$k] = [
                    "tripId" => $v['id'],
                    "duration" => $v['duration'],
                    "nights" => $v['nights'],
                    'arrivalDate' => strtotime($v['end_time']),
                    'departureDate' => strtotime($v['start_time']),
                    "title" => $v['name_cn'],
                    "availableCabinsCount" => 5,
                    "price" => 1,
                    "rest" => $v['free_spaces'] > 0 ? (int)$v['free_spaces'] : -1,
                ];
                $tripIds[] = $v['id'];
            }
            $tripsMap[$boatId] = $r;
        }
        $priceMap = Occupancy::getTripsPrice($tripIds);
        $minPrice = min($priceMap);
        foreach ($tripsMap as $k => $trips) {
            foreach ($trips as $k2 => $trip) {
                if (!isset($priceMap[$trip['tripId']])) {
                    Yii::warning("Trip {$trip['tripId']} Have No Price", __METHOD__);
                }
                $trips[$k2]['price'] = $priceMap[$trip['tripId']] ?? $minPrice;
            }
            $tripsMap[$k] = $trips;
        }
        return $tripsMap;
    }

    public static function getTrip($tripId) {
        $r = TripModel::getList("id=$tripId");
        $list = self::format($r);
        $boat = Boat::getBasicInfo($r[0]['boat_id']);
        return [
            'list' => $list,
            'features' => [],
            'boatName' => $boat['name_cn'],
            'boatNameEN' => $boat['name_en'],
            'boatImage' => $boat['main_image'],
        ];
    }

    private static function format($r) {
        $trips = $tours = [];
        foreach ($r as $k => $v) {
            $tmp = [
                'arrivalDate' => strtotime($v['end_time']),
                'tripId' => $v['id'],
                'tourId' => $v['tour_id'],
                'departureDate' => strtotime($v['start_time']),
                'duration' => 1,
                'nights' => 1,
                'title' => 'test',
                'dives' => 1,
                'availableCount' => $v['free_spaces'],
                'nameEN' => $v['name_en'],
                'nameCN' => $v['name_cn'],
                //'includes' => $v['includes'],
                //'excludes' => $v['excludes'],
                'feature' => empty($v['feature_json']) ? [] : json_decode($v['feature_json'], true),
                'policy' => $v['policy'],
            ];
            $v['tour_id'] != 0 && $trips[]=$tmp;
        }

        $tourData = Tour::getTours(array_column($trips, 'tourId'));
        foreach ($tourData as $k => $v) {
            $tours[$v['id']] = [
                'id' => $v['id'],
                'arrivalLocation' => $v['arrival_cn'],
                'departureLocation' => $v['departure_cn'],
                'arrivalPort' => $v['arrival_port'],
                'departurePort' => $v['departure_port'],
                'name_cn' => $v['name_cn'],
                'name_en' => $v['name_en'],
                'diveNumDesc' => $v['dives'],
                'photos' => json_decode($v['images'], true),
                'experience' => $v['experience'],
                'sertification' => explode(' ', $v['sertification'])[0],
                'dives' => $v['dives'],
                'duration' => $v['duration'],
                'nights' => $v['nights'],
                'included_cn' => $v['included_cn'],
                'notincluded_cn' => $v['notincluded_cn'],
                'programm' => $v['programm'],
                'check_in' => $v['check_in'],
                'check_out' => $v['check_out'],
            ];
        }
        //$features['rental'] = TripProductRel::getRental($tripId);
        foreach ($trips as $k => $v) {
            $trips[$k]['tour'] = $tours[$v['tourId']];
        }

        //价格
        $priceMap = Occupancy::getTripsPrice(array_column($trips, 'tripId'));
        $minPrice = empty($priceMap) ? 0 : (int)min($priceMap);
        foreach ($trips as $k => $trip) {
            $trips[$k]['price'] = [
                'value' => isset($priceMap[$trip['tripId']]) ? (int)$priceMap[$trip['tripId']] : $minPrice,
                'unit' => '￥'
            ];
        }
        return $trips;
    }

    public static function getIds($boatId, $startMonth) {
        if (empty($boatId) || empty($startMonth)) {
            return [
                'err' => 1,
                '参数错误'
            ];
        }
        return TripModel::getColumn("boat_id=$boatId AND start_time LIKE '$startMonth%'", 'id');
    }

    public static function getTourIds($boatId, $startMonth) {
        if (empty($boatId) || empty($startMonth)) {
            return [
                'err' => 1,
                '参数错误'
            ];
        }
        return TripModel::getColumn("boat_id=$boatId AND start_time LIKE '$startMonth%'", 'tour_id');
    }
    public static function getOneTrip($tripId){
        return TripModel::getOne("id=$tripId");
    }
    public static function getBoatName($tripId){
        $boatId = Trip::getBoatId($tripId);
        $info = Boat::getBasicInfo($boatId);
        return $info['name_cn'] ?: $info['name_en'];
    }
}
